<template>
  <el-dialog
    v-model="visible"
    :title="$t('coupon.edit')"
    :close-on-click-modal="false"
    class="dialog-add-or-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-position="left"
      label-width="auto"
      @submit.prevent
    >
      <!-- 订单id -->
      <el-form-item
        :label="$t('order.number') + '：'"
        prop="orderNumber"
      >
        <div>{{ dataForm.orderNumber || '' }}</div>
      </el-form-item>
      <!-- 发票类型 1.电子普通发票 -->
      <el-form-item
        :label="$t('order.invoiceType') + '：'"
        prop="invoiceType"
      >
        <div v-if="dataForm.invoiceType === 1">
          {{ $t('order.normalInvoiceType') }}
        </div>
      </el-form-item>
      <!-- 抬头类型 1.单位 2.个人 -->
      <el-form-item
        :label="$t('order.headerType') + '：'"
        prop="headerType"
      >
        <div>{{ ['', $t('order.unit'), $t('order.personal')][dataForm.headerType] }}</div>
      </el-form-item>
      <!-- 抬头名称 -->
      <el-form-item
        v-if="dataForm.headerName"
        :label="$t('order.headerName') + '：'"
        prop="headerName"
      >
        <div>{{ dataForm.headerName || '' }}</div>
      </el-form-item>
      <!-- 发票税号 -->
      <el-form-item
        v-if="dataForm.invoiceTaxNumber && dataForm.headerType === 1"
        :label="$t('order.invoiceTaxNumber') + '：'"
        prop="invoiceTaxNumber"
      >
        <div>{{ dataForm.invoiceTaxNumber || '' }}</div>
      </el-form-item>
      <!-- 订单状态 -->
      <el-form-item
        :label="$t('order.orderStatus') + '：'"
        prop="orderStatus"
      >
        <span v-if="dataForm.orderStatus === 1">{{ $t('order.pendingPayment') }}</span>
        <span v-if="dataForm.orderStatus === 2">{{ $t('order.toBeShipped') }}</span>
        <span v-if="dataForm.orderStatus === 3">{{ $t('order.pendingReceipt') }}</span>
        <span v-if="dataForm.orderStatus === 4">{{ $t('order.toBeEvaluated') }}</span>
        <span v-if="dataForm.orderStatus === 5">{{ $t('order.success') }}</span>
        <span v-if="dataForm.orderStatus === 6">{{ $t('order.fail') }}</span>
        <span v-if="dataForm.orderStatus === 7">{{ $t('group.waitGroup') }}</span>
      </el-form-item>
      <!-- 发票状态 1.申请中 2.已开票 -->
      <el-form-item
        :label="$t('order.invoiceStatus') + '：'"
        prop="invoiceState"
      >
        <div>
          {{
            ['', $t('order.applicationInProgress'), $t('order.invoiceIssued')][
              dataForm.invoiceState
            ]
          }}
        </div>
      </el-form-item>
      <!-- 发票上传： -->
      <el-form-item :label="$t('order.invoiceUpload') + '：'">
        <div class="invoiceUpload-item">
          <a
            v-if="fileInfo.filePath"
            target="_blank"
            :href="resourcesUrl + fileInfo.filePath"
            class="pdfLink"
          >{{ fileInfo.fileName }}</a>
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            accept=".pdf"
            action=""
            :headers="{ Authorization: cookie.get('b2cAuthorization'), locale: lang }"
            :multiple="false"
            :auto-upload="false"
            :limit="1"
            :http-request="handleFileChange"
            :before-upload="onBeforeUpload"
          >
            <template #trigger>
              <el-button type="primary">
                {{ $t('order.SelectFile') }}
              </el-button>
            </template>
            <el-button
              v-if="isAuth('order:orderInvoice:upload')"
              style="margin-left: 10px"
              type="success"
              @click="onUploadConfirm"
            >
              {{ $t('components.confirmUpload') }}
              <el-tooltip
                :content="$t('components.uploadPDF')"
                placement="top"
                effect="light"
              >
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </el-button>
          </el-upload>
        </div>
      </el-form-item>
      <!-- 申请时间 -->
      <el-form-item
        :label="$t('order.applicationTime') + '：'"
        prop="applicationTime"
      >
        <div>{{ dataForm.applicationTime }}</div>
      </el-form-item>
      <!-- 上传时间 -->
      <el-form-item
        v-if="dataForm.uploadTime"
        :label="$t('order.uploadTime') + '：'"
        prop="uploadTime"
      >
        <div>{{ dataForm.uploadTime }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          v-if="isAuth('order:orderInvoice:commit')"
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'
import cookie from 'vue-cookies'
import http from '@/utils/http.js'
const emit = defineEmits(['refreshDataList'])
const lang = ref(localStorage.getItem('b2cLang') || 'zh_CN')
const resourcesUrl = ref(import.meta.env.VITE_APP_RESOURCES_URL)
const visible = ref(false)
const dataForm = ref({
  orderInvoiceId: 0,
  orderNumber: null,
  shopId: null,
  invoiceType: null,
  headerType: null,
  headerName: null,
  invoiceTaxNumber: null,
  invoiceState: null,
  fileId: null,
  applicationTime: null,
  uploadTime: null,
  ossList: null,
  attachFile: null
})
const fileInfo = ref({})

const init = orderInvoiceId => {
  visible.value = true
  nextTick(() => {
    onResetDataFrom()
    if (!orderInvoiceId) {
      return
    }
    dataForm.value.orderInvoiceId = orderInvoiceId || 0
    http({
      url: http.adornUrl(`/m/orderInvoice/info/${orderInvoiceId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      // 请求文件
      if (dataForm.value.fileId) {
        http({
          url: http.adornUrl('/admin/file/get_file_by_id'),
          method: 'get',
          params: http.adornParams({
            fileId: dataForm.value.fileId
          })
        }).then(({ data }) => {
          fileInfo.value = data
        })
      }
    })
  })
}
// 清空数据
const onResetDataFrom = () => {
  dataForm.value = {
    orderInvoiceId: 0,
    orderNumber: null,
    shopId: null,
    invoiceType: null,
    headerType: null,
    headerName: null,
    invoiceTaxNumber: null,
    invoiceState: null,
    fileId: null,
    applicationTime: null,
    uploadTime: null,
    ossList: null,
    attachFile: null
  }
  fileInfo.value = {}
}
// 表单提交
const dataFormRef = ref(null)
const onSubmit = () => {
  dataFormRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    http({
      url: http.adornUrl('/m/orderInvoice'),
      method: 'put',
      data: dataForm.value
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1000,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
        }
      })
    })
  })
}
/**
 * 上传图片
 */
const uploadRef = ref(null)
const fileList = ref([])
const onUploadConfirm = () => {
  if (fileList.value?.length < 1) {
    return ElMessage.error($t('order.uploadInvoiceTip'))
  }
  if (dataForm.value.orderStatus < 4) {
    ElMessageBox.confirm($t('order.uploadInvoiceTip1'), $t('remindPop.remind'), {
      confirmButtonText: $t('remindPop.confirm'),
      cancelButtonText: $t('remindPop.cancel'),
      type: 'warning'
    }).then(() => {
      uploadRef.value?.submit()
    })
  } else {
    uploadRef.value?.submit()
  }
}
const handleFileChange = (e) => {
  const file = e.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(({ data }) => {
    uploadFile(data.preSignUrl, file).then(() => {
      http({
        url: http.adornUrl('/admin/file/uploadSuccess'),
        method: 'put',
        data: [{
          fileId: data.fileId,
          attachFileGroupId: 0,
          type: 1,
          fileSize: file.size
        }]
      }).then(() => {
        fileInfo.value = {
          filePath: data.filePath,
          fileName: file.name
        }
        dataForm.value.fileId = data.fileId
        uploadRef.value.uploadFiles = []
        fileList.value = []
      }).catch((err) => {
        ElMessage($t('biz.imgbox.requestError'), true)
        throw err
      })
    })
  })
}

/**
 * 上传前检查合法性
 * @param file
 * @returns {boolean}
 */
const onBeforeUpload = file => {
  const isImage = file.type === 'application/pdf'
  if (!isImage) {
    ElMessage.error($t('order.PleaseUploadPDFFile'))
    return false
  }
  return true
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.dialog-add-or-update {
  .pdfLink {
    color: #606266;
  }
  .pdfLink:hover {
    color: #155bd4;
  }
  .invoiceUpload-item{
    flex: 1;
  }
}
</style>
